import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/auth/LoginView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/auth/RegisterView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/big-screen',
      name: 'BigScreen',
      component: () => import('@/views/BigScreen.vue'),
      meta: { requiresAuth: true }
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  if (to.meta.requiresAuth) {
    if (!userStore.isAuthenticated) {
      try {
        await userStore.checkStatus()
        next()
      } catch (error) {
        next('/login')
      }
    } else {
      next()
    }
  } else {
    if (userStore.isAuthenticated && (to.path === '/login' || to.path === '/register')) {
      next('/big-screen')
    } else {
      next()
    }
  }
})

export default router
